package com.kgc.itrip.component;

import com.kgc.itrip.common.Constants;
import com.kgc.itrip.common.MD5;
import com.kgc.itrip.pojo.ItripUser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Token验证
 * Created by hanlu on 2017/5/7.
 */
@Slf4j
@Data
@Component
public class ValidationToken {
    @Resource
    private RedisTools redisAPI;


    public ItripUser getCurrentUser(String tokenString){
        //根据token从redis中获取用户信息
			/*
			 test token:
			 key : token:1qaz2wsx
			 value : {"id":"100078","userCode":"myusercode","userPassword":"78ujsdlkfjoiiewe98r3ejrf","userType":"1","flatID":"10008989"}

			*/
        ItripUser itripUser = null;
        if(null == tokenString || "".equals(tokenString)){
            return null;
        }
        try{
            itripUser = redisAPI.getObject(tokenString,ItripUser.class);
        }catch(Exception e){
            itripUser = null;
            log.error("get userinfo from redis but is error : " + e.getMessage());
        }
        return itripUser;
    }

    private boolean exists(String token) {
        return redisAPI.get(token)!=null ? true : false;
    }

    public boolean validate(String agent, String token) {
        if (!exists(token)) {// token不存在
            return false;
        }
        try {
            Date TokenGenTime;// token生成时间
            String agentMD5;
            String[] tokenDetails = token.split("-");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            TokenGenTime = formatter.parse(tokenDetails[3]);
            long passed = Calendar.getInstance().getTimeInMillis()
                    - TokenGenTime.getTime();
            if(passed> Constants.SESSION_TIMEOUT*1000)
                return false;
            agentMD5 = tokenDetails[4];
            if(MD5.getMd5(agent, 6).equals(agentMD5))
                return true;
        } catch (ParseException e) {
            return false;
        }
        return false;
    }

}
